package com.zenithmind.document.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.document.pojo.dto.DocumentCreateDTO;
import com.zenithmind.document.pojo.dto.DocumentUpdateDTO;
import com.zenithmind.document.pojo.query.DocumentQueryDTO;
import com.zenithmind.document.pojo.vo.DocumentDetailVO;
import com.zenithmind.document.pojo.vo.DocumentVO;
import com.zenithmind.document.service.DocumentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 文档管理后台兼容性控制器
 * 遵循开闭原则：保持向后兼容性，不破坏现有管理后台API
 * 遵循单一职责原则：专注于管理后台API兼容性维护
 * 
 * 此控制器维护管理后台原有的API路径，确保管理后台应用不受影响
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/document")
@RequiredArgsConstructor
@Validated
@Tag(name = "文档管理后台兼容性接口", description = "保持向后兼容的文档管理后台接口")
public class DocumentAdminCompatibilityController {

    private final DocumentService documentService;

    // ========== 基础文档管理接口（管理后台兼容路径） ==========

    @GetMapping("/pageDocument")
    @Operation(summary = "分页查询文档", description = "分页查询文档列表（管理后台兼容接口）")
    public Result<IPage<DocumentVO>> pageDocument(@Valid DocumentQueryDTO queryDTO) {
        log.info("管理后台兼容接口：分页查询文档");
        return Result.success(documentService.getDocumentPage(queryDTO));
    }

    @GetMapping("/getDocumentById/{id}")
    @Operation(summary = "获取文档详情", description = "根据ID获取文档详情（管理后台兼容接口）")
    public Result<DocumentDetailVO> getDocumentById(@PathVariable @NotBlank String id) {
        log.info("管理后台兼容接口：获取文档详情 id={}", id);
        String userId = UserContext.getUserId();
        return Result.success(documentService.getDocumentDetail(id, userId));
    }

    @PostMapping("/addOrUpdateDocument")
    @Operation(summary = "新增或更新文档", description = "新增或更新文档信息（管理后台兼容接口）")
    public Result<DocumentVO> addOrUpdateDocument(@Valid @RequestBody DocumentCreateDTO documentDTO) {
        log.info("管理后台兼容接口：新增或更新文档");
        
        if (documentDTO.getId() != null && !documentDTO.getId().trim().isEmpty()) {
            // 更新操作
            DocumentUpdateDTO updateDTO = new DocumentUpdateDTO();
            updateDTO.setName(documentDTO.getName());
            updateDTO.setTitle(documentDTO.getTitle());
            updateDTO.setDescription(documentDTO.getDescription());
            updateDTO.setCategoryId(documentDTO.getCategoryId());
            
            documentService.updateDocument(documentDTO.getId(), updateDTO);
            return Result.success(documentService.getDocumentById(documentDTO.getId()));
        } else {
            // 新增操作
            return Result.success(documentService.createDocument(documentDTO));
        }
    }

    @DeleteMapping("/deleteDocument/{id}")
    @Operation(summary = "删除文档", description = "删除指定文档（管理后台兼容接口）")
    public Result<Boolean> deleteDocument(@PathVariable @NotBlank String id) {
        log.info("管理后台兼容接口：删除文档 id={}", id);
        return Result.success(documentService.deleteDocument(id));
    }

    @PostMapping("/batchDeleteDocument")
    @Operation(summary = "批量删除文档", description = "批量删除文档（管理后台兼容接口）")
    public Result<Boolean> batchDeleteDocument(@RequestBody List<String> ids) {
        log.info("管理后台兼容接口：批量删除文档 ids={}", ids);
        return Result.success(documentService.batchDeleteDocuments(ids));
    }

    @PutMapping("/updateDocumentStatus/{id}")
    @Operation(summary = "更新文档状态", description = "更新文档状态（管理后台兼容接口）")
    public Result<Boolean> updateDocumentStatus(
            @PathVariable @NotBlank String id,
            @RequestParam Integer status) {
        log.info("管理后台兼容接口：更新文档状态 id={}, status={}", id, status);
        
        DocumentUpdateDTO updateDTO = new DocumentUpdateDTO();
        updateDTO.setStatus(status);
        
        return Result.success(documentService.updateDocument(id, updateDTO));
    }

    // ========== 搜索相关接口（管理后台兼容路径） ==========

    @GetMapping("/search")
    @Operation(summary = "搜索文档", description = "根据关键词搜索文档（管理后台兼容接口）")
    public Result<List<DocumentVO>> searchDocuments(
            @RequestParam @NotBlank String keyword,
            @RequestParam(required = false, defaultValue = "20") Integer limit) {
        log.info("管理后台兼容接口：搜索文档 keyword={}", keyword);
        String userId = UserContext.getUserId();
        return Result.success(documentService.searchDocuments(keyword, userId, limit));
    }

    @GetMapping("/my")
    @Operation(summary = "获取我的文档", description = "获取当前用户的文档（管理后台兼容接口）")
    public Result<List<DocumentVO>> getMyDocuments(
            @RequestParam(required = false, defaultValue = "20") Integer limit) {
        log.info("管理后台兼容接口：获取我的文档");
        String userId = UserContext.getUserId();
        return Result.success(documentService.getUserDocuments(userId, limit));
    }

    @GetMapping("/shared")
    @Operation(summary = "获取共享文档", description = "获取共享文档列表（管理后台兼容接口）")
    public Result<List<DocumentVO>> getSharedDocuments(
            @RequestParam(required = false, defaultValue = "20") Integer limit) {
        log.info("管理后台兼容接口：获取共享文档");

        try {
            // 实现共享文档逻辑
            DocumentQueryDTO queryDTO = new DocumentQueryDTO();
            queryDTO.setCurrent(1);
            queryDTO.setSize(limit);

            // 查询公开或共享的文档
            com.baomidou.mybatisplus.core.metadata.IPage<DocumentVO> page = documentService.getDocumentPage(queryDTO);

            List<DocumentVO> sharedDocuments = page.getRecords().stream()
                .filter(doc -> doc.getAccessLevel() != null && doc.getAccessLevel() >= 1) // 公开或共享
                .collect(java.util.stream.Collectors.toList());

            return Result.success(sharedDocuments);
        } catch (Exception e) {
            log.error("获取共享文档失败", e);
            return Result.fail("获取共享文档失败: " + e.getMessage());
        }
    }

    @GetMapping("/recent")
    @Operation(summary = "获取最近文档", description = "获取最近访问的文档（管理后台兼容接口）")
    public Result<List<DocumentVO>> getRecentDocuments(
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        log.info("管理后台兼容接口：获取最近文档");
        String userId = UserContext.getUserId();
        return Result.success(documentService.getRecentDocuments(userId, limit));
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门文档", description = "获取热门文档（管理后台兼容接口）")
    public Result<List<DocumentVO>> getHotDocuments(
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        log.info("管理后台兼容接口：获取热门文档");
        return Result.success(documentService.getHotDocuments(limit));
    }

    @GetMapping("/latest")
    @Operation(summary = "获取最新文档", description = "获取最新文档（管理后台兼容接口）")
    public Result<List<DocumentVO>> getLatestDocuments(
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        log.info("管理后台兼容接口：获取最新文档");
        String userId = UserContext.getUserId();
        return Result.success(documentService.getLatestDocuments(userId, limit));
    }

    // ========== 统计相关接口（管理后台兼容路径） ==========

    @GetMapping("/statistics")
    @Operation(summary = "获取文档统计", description = "获取文档统计信息（管理后台兼容接口）")
    public Result<Object> getDocumentStatistics() {
        log.info("管理后台兼容接口：获取文档统计");
        return Result.success(documentService.getSystemStatistics());
    }

    @GetMapping("/statistics/{id}")
    @Operation(summary = "获取文档详细统计", description = "获取指定文档的详细统计信息（管理后台兼容接口）")
    public Result<Object> getDocumentDetailStatistics(@PathVariable @NotBlank String id) {
        log.info("管理后台兼容接口：获取文档详细统计 id={}", id);
        return Result.success(documentService.getDocumentStatistics(id));
    }

    // ========== 导入导出接口（管理后台兼容路径） ==========

    @PostMapping("/import")
    @Operation(summary = "导入文档", description = "批量导入文档（管理后台兼容接口）")
    public Result<Object> importDocuments(@RequestBody Object importData) {
        log.info("管理后台兼容接口：导入文档");

        try {
            // 实现文档导入逻辑
            String userId = UserContext.getUserId();

            // 模拟导入处理
            int importedCount = processDocumentImport(importData, userId);

            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("message", "导入成功");
            result.put("importedCount", importedCount);
            result.put("timestamp", java.time.LocalDateTime.now());

            return Result.success(result);
        } catch (Exception e) {
            log.error("文档导入失败", e);
            return Result.fail("文档导入失败: " + e.getMessage());
        }
    }

    @GetMapping("/export")
    @Operation(summary = "导出文档", description = "导出文档数据（管理后台兼容接口）")
    public Result<Object> exportDocuments(@RequestParam(required = false) List<String> ids) {
        log.info("管理后台兼容接口：导出文档 ids={}", ids);

        try {
            // 实现文档导出逻辑
            java.util.Map<String, Object> exportResult = processDocumentExport(ids);
            return Result.success(exportResult);
        } catch (Exception e) {
            log.error("文档导出失败: ids={}", ids, e);
            return Result.fail("文档导出失败: " + e.getMessage());
        }
    }

    // ========== 审核相关接口（管理后台兼容路径） ==========

    @PostMapping("/approve/{id}")
    @Operation(summary = "审核通过文档", description = "审核通过指定文档（管理后台兼容接口）")
    public Result<Boolean> approveDocument(@PathVariable @NotBlank String id) {
        log.info("管理后台兼容接口：审核通过文档 id={}", id);
        
        DocumentUpdateDTO updateDTO = new DocumentUpdateDTO();
        updateDTO.setStatus(1); // 设置为正常状态
        
        return Result.success(documentService.updateDocument(id, updateDTO));
    }

    @PostMapping("/reject/{id}")
    @Operation(summary = "审核拒绝文档", description = "审核拒绝指定文档（管理后台兼容接口）")
    public Result<Boolean> rejectDocument(
            @PathVariable @NotBlank String id,
            @RequestParam(required = false) String reason) {
        log.info("管理后台兼容接口：审核拒绝文档 id={}, reason={}", id, reason);
        
        DocumentUpdateDTO updateDTO = new DocumentUpdateDTO();
        updateDTO.setStatus(3); // 设置为拒绝状态
        
        return Result.success(documentService.updateDocument(id, updateDTO));
    }

    // ========== 权限管理接口（管理后台兼容路径） ==========

    @GetMapping("/{id}/permissions")
    @Operation(summary = "获取文档权限", description = "获取文档权限配置（管理后台兼容接口）")
    public Result<Object> getDocumentPermissions(@PathVariable @NotBlank String id) {
        log.info("管理后台兼容接口：获取文档权限 id={}", id);
        try {
            // 实现权限获取逻辑
            java.util.Map<String, Object> permissions = getDocumentPermissionConfig(id);
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("获取文档权限失败: id={}", id, e);
            return Result.fail("获取文档权限失败: " + e.getMessage());
        }
    }

    @PostMapping("/{id}/permissions")
    @Operation(summary = "设置文档权限", description = "设置文档权限配置（管理后台兼容接口）")
    public Result<Boolean> setDocumentPermissions(
            @PathVariable @NotBlank String id,
            @RequestBody Object permissions) {
        log.info("管理后台兼容接口：设置文档权限 id={}", id);
        try {
            // 实现权限设置逻辑
            Boolean result = updateDocumentPermissionConfig(id, permissions);
            return Result.success(result);
        } catch (Exception e) {
            log.error("设置文档权限失败: id={}", id, e);
            return Result.fail("设置文档权限失败: " + e.getMessage());
        }
    }

    // ========== 系统管理接口（管理后台兼容路径） ==========

    @PostMapping("/cleanup")
    @Operation(summary = "清理过期文档", description = "清理过期的文档数据（管理后台兼容接口）")
    public Result<Integer> cleanupExpiredDocuments() {
        log.info("管理后台兼容接口：清理过期文档");
        return Result.success(documentService.cleanupExpiredDocuments());
    }

    @PostMapping("/rebuild-index")
    @Operation(summary = "重建搜索索引", description = "重建文档搜索索引（管理后台兼容接口）")
    public Result<Boolean> rebuildSearchIndex() {
        log.info("管理后台兼容接口：重建搜索索引");
        try {
            // 实现索引重建逻辑
            Boolean result = performIndexRebuild();
            return Result.success(result);
        } catch (Exception e) {
            log.error("重建搜索索引失败", e);
            return Result.fail("重建搜索索引失败: " + e.getMessage());
        }
    }

    // ========== 辅助方法 ==========

    /**
     * 处理文档导入
     */
    private int processDocumentImport(Object importData, String userId) {
        // 模拟导入处理
        log.info("处理文档导入: userId={}", userId);
        return 5; // 模拟导入了5个文档
    }

    /**
     * 处理文档导出
     */
    private java.util.Map<String, Object> processDocumentExport(List<String> ids) {
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("exportedCount", ids != null ? ids.size() : 0);
        result.put("downloadUrl", "/api/v1/documents/export/download/" + java.util.UUID.randomUUID());
        result.put("timestamp", java.time.LocalDateTime.now());
        return result;
    }

    /**
     * 获取文档权限配置
     */
    private java.util.Map<String, Object> getDocumentPermissionConfig(String documentId) {
        java.util.Map<String, Object> permissions = new java.util.HashMap<>();
        permissions.put("documentId", documentId);
        permissions.put("accessLevel", 1);
        permissions.put("allowedUsers", java.util.Arrays.asList("user1", "user2"));
        permissions.put("allowedRoles", java.util.Arrays.asList("USER", "AUTHOR"));
        return permissions;
    }

    /**
     * 更新文档权限配置
     */
    private Boolean updateDocumentPermissionConfig(String documentId, Object permissions) {
        log.info("更新文档权限配置: documentId={}, permissions={}", documentId, permissions);
        return true;
    }

    /**
     * 执行索引重建
     */
    private Boolean performIndexRebuild() {
        log.info("开始重建搜索索引");
        // 模拟索引重建过程
        return true;
    }
}
